package com.clip.service;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import net.sf.jml.MsnContact;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.clip.dao.ContactDAO;
import com.clip.dao.ContactGroupDAO;
import com.clip.dao.ContactGroupMappingDAO;
import com.clip.dao.ContactTypeDAO;
import com.clip.dao.SharemappingDAO;
import com.clip.dao.UserDAO;
import com.clip.dao.UserEmailCollectionDAO;
import com.clip.dao.UserEmailDAO;
import com.clip.dao.UserEmailEventDAO;
import com.clip.dao.UsermobileinfoDAO;
import com.clip.entity.Contact;
import com.clip.entity.ContactGroup;
import com.clip.entity.ContactGroupMapping;
import com.clip.entity.ContactType;
import com.clip.entity.User;
import com.clip.entity.UserEmail;
import com.clip.entity.UserEmailCollection;
import com.clip.entity.UserEmailEvent;
import com.clip.entity.Userassina;
import com.clip.entity.Usermobileinfo;
import com.clip.entity.appcontact.AppContact;
import com.clip.entity.appcontact.AppEmail;
import com.clip.entity.appcontact.AppPhone;
import com.clip.entity.appcontact.AppWeibo;
import com.clip.util.ToolsUtils;
import com.clip.util.json.JSONArray;
import com.clip.util.json.JSONObject;
import com.clip.util.mail.SimpleMailSender;

@Service
@Transactional
public class ContactService {
	@Autowired
	private ContactDAO contactDAO;
	@Autowired
	private UserDAO userDAO;
	@Autowired
	private ContactTypeDAO contactTypeDAO;
	@Autowired
	private UserEmailEventDAO userEmailEventDAO;
	@Autowired
	private UserEmailDAO userEmailDAO;
	@Autowired
	private UserEmailCollectionDAO userEmailCollectionDAO;
	@Autowired
	private UsermobileinfoDAO usermobileinfoDAO;
	@Autowired
	private ContactGroupMappingDAO contactGroupMappingDAO;
	@Autowired
	private SharemappingDAO sharemappingDAO;
	@Autowired
	private ContactGroupDAO contactGroupDAO;
	public static int CONTACTPAGINGSIZE=9; 
	
	public static int APPCONTACTLENGTH=10;
	public void saveUserEmailcollect(UserEmailCollection uec){
		userEmailCollectionDAO.saveNotExists(uec);
	}
	
	public List<Contact> getContactByEmail(String email){
		return contactDAO.findByContactEmail(email);
	}
	public List<Contact> getContactByEmailAndUid(String email,Integer uid){
		return contactDAO.findByQuery("from Contact c where c.contactemail='"+email+"' and c.uid="+uid);
	}
	
	public Contact getContactById(Integer id){
		return contactDAO.findById(id);
	}
	public void deleteContact(Contact contact){
		contactDAO.delete(contact);
	}
	/**
	 * 获取联系人
	 * @param user 登录用户
	 * @return
	 */
	public Map<String,Object> loadContactAll(User user){
		Map<String,Object> contactMap = new LinkedHashMap<String, Object>();
		String hql="";
		if(user.getUsertype()==1)
			hql="select a FROM Contact a, Contact b where a.uid="+user.getId()+" and a.uid=b.contactuid and a.contactuid=b.uid and a.status=1 and b.status=1 order by a.pinyinname";
		else
			hql="FROM Contact a where a.uid="+user.getId()+" and a.status=1 and a.contacttypeid=2 order by a.pinyinname";
		List<Contact> newList=this.contactDAO.findByQuery(hql);
		hql = "from ContactGroup cg where cg.uid="+user.getId()+" order by cg.pinyingroupname";
		List<ContactGroup> grouplist=this.contactGroupDAO.findByQuery(hql);
		
		for(Contact con : newList){
			int uid=con.getContactuid();
			hql="FROM User u where u.id="+uid+" and u.status=1";
			List<User> UList = this.contactDAO.findByQuery(hql);
			if(UList!=null&&UList.size()>0){
				Map<String,Object> map=new HashMap<String,Object>();
				map.put("name", con.getName());
				map.put("pinyinname", con.getPinyinname());
				map.put("email", con.getContactemail());
				map.put("hasmobile", false);
				map.put("uid",uid);
				map.put("logo", ToolsUtils.xmlCDATA(UserService.getUserLogoByUid(uid).get(1)));
				contactMap.put("Contact id="+con.getId(), map);
			}else{
				this.contactDAO.delete(con);
				newList.remove(con);
			}
		}
		for (int i = 0; i < grouplist.size(); i++) {
			ContactGroup contactGroup=grouplist.get(i);
			Map temp2=new HashMap();
			temp2.put("groupname", contactGroup.getGroupname());
			temp2.put("pinyingroupname", contactGroup.getPinyingroupname());
			temp2.put("membercount", contactGroup.getMembercount());
			List templist=this.contactGroupMappingDAO.findByQuery("from ContactGroupMapping map where map.groupid="+contactGroup.getId());
			for (Object object : templist) {
				Map temp3=new HashMap();
				ContactGroupMapping mapping=(ContactGroupMapping) object;
				int contactid=getContactId(newList,mapping.getContactuid());
				if(contactid==0){
					this.contactGroupMappingDAO.delete(mapping);
				}else
					temp2.put("groupContact id="+contactid, temp3);
			}
			contactMap.put("ContactGroup id="+contactGroup.getId(), temp2);
		}
		return contactMap;
	}
	
	private int getContactId(List contactlist,int contactuid){
		int contactid=0;
		for (Object object : contactlist) {
			Contact c=(Contact) object;
			if(c.getContactuid()==contactuid){
				contactid=c.getId();
				break;
			}
		}
		return contactid;
	}
	
	public boolean isHasBindableMobile(Integer uid){
		String query="from Usermobileinfo info where info.uid='"+uid+"' and info.status=1";
		List list=usermobileinfoDAO.findByQuery(query);
		if(list==null||list.size()<=0){
			return false;
		}else{
			return true;
			
		}
	}
	
	public Map<String,Object> getContactType(User user){
		Map<String,Object> map = new LinkedHashMap<String, Object>();
		List<ContactType> ctList = contactTypeDAO.findAll();
		for(ContactType ct : ctList){
			String hql = "";
			if(ct.getId()==4){
				hql = "SELECT COUNT(c.id) FROM Contact c where c.uid="+user.getId()+" and (c.status=0 or c.contacttypeid=4)";
			}else{
				hql = "SELECT COUNT(c1.id) FROM Contact c1,Contact c2 WHERE c1.uid="+user.getId()+" AND c1.contacttypeid="+ct.getId()+" AND c1.uid=c2.contactuid AND c2.uid=c1.contactuid AND c1.status=1";
			}
			Map<String,Object> ctMap=new HashMap<String,Object>();
			ctMap.put("id", ct.getId());
			ctMap.put("name", ct.getTypename());
			ctMap.put("dataCount", this.contactTypeDAO.getQuery(hql).uniqueResult());
			map.put("type id="+ct.getId(), ctMap);
		}
		return map;
	}
	/**
	 * 获得联系人
	 * @param user 登录用户
	 * @param typeId 关系
	 * @return
	 */
	public Map<String,Object> getUserContact(User currentUser,Integer typeId,int currentpage){
		Map<String,Object> contactMap = new LinkedHashMap<String, Object>();
		String hql="";
		List<Contact> list = new ArrayList<Contact>();
		List<Contact> newList= new ArrayList<Contact>();
		if(typeId==4){
			hql="FROM Contact c where c.uid="+currentUser.getId()+" and c.status=0";
			newList=contactDAO.pagingByQuery(hql,currentpage,ContactService.CONTACTPAGINGSIZE);
			for(Contact con : newList){
				Map<String,Object> map=new HashMap<String,Object>();
				map.put("id", con.getId());
				map.put("name", "<![CDATA["+con.getName()+"]]>");
				map.put("email", con.getContactemail());
				
				map.put("uEmail", "");
				map.put("uName", "陌生人");
				String biglogo=(String) UserService.getUserLogoByUid(con.getContactuid()).get(0);
				map.put("ulogo",ToolsUtils.xmlCDATA(biglogo));
				map.put("status", 0);
				contactMap.put("Contact id="+con.getId(), map);
			}
		}else{
			hql = "SELECT c1 FROM Contact c1,Contact c2 WHERE c1.uid="+currentUser.getId()+" AND c1.uid=c2.contactuid AND c2.uid=c1.contactuid AND c1.status=1 AND c2.status=1 order by c1.pinyinname";
			newList=contactDAO.pagingByQuery(hql,currentpage,ContactService.CONTACTPAGINGSIZE);
			for(Contact con : newList){
				hql="FROM User u where u.id="+con.getContactuid()+" and u.status=1";
				List<User> UList = contactDAO.findByQuery(hql);
				if(UList!=null&&UList.size()>0){
					User user = UList.get(0);
					if(user!=null){
						Map<String,Object> map=new HashMap<String,Object>();
						map.put("id", con.getId());
						map.put("name", "<![CDATA["+con.getName()+"]]>");
						map.put("email", con.getContactemail());
						String query="from Usermobileinfo info where info.uid='"+user.getId()+"' and info.status=1";
						List ml=usermobileinfoDAO.findByQuery(query);
						Usermobileinfo usermobileinfo= ml!=null&&ml.size()>0?(Usermobileinfo)ml.get(0):null;
						map.put("mobile",usermobileinfo!=null?usermobileinfo.getMobilenum():"");
						map.put("uEmail", user.getEmail());
						map.put("uid", user.getId());
						map.put("uName", "<![CDATA["+user.getName()+"]]>");
						map.put("birth",user.getBirth()!=null?user.getBirth():0);
						map.put("qq", user.getQq());
						String biglogo=(String) UserService.getUserLogoByUid(user.getId()).get(0);
						map.put("ulogo",ToolsUtils.xmlCDATA(biglogo));
						contactMap.put("Contact id="+con.getId(), map);
					}
				}
			}
		}
		
		return contactMap;
	}
	
	/**
	 * 删除联系人
	 * @param user 登录用户
	 * @param id 联系人
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String delContactByContactId(User user,Integer id){
		String result="{result:'删除失败',flag:0}";
		String hql="FROM Contact c where c.id="+id+" and c.uid="+user.getId();
		List<Contact> myContact = contactDAO.findByQuery(hql);//找到对方是我好友的数据
		if(myContact!=null&&myContact.size()>0){
			Contact c=myContact.get(0);
			hql="FROM Contact c where c.uid="+c.getContactuid()+" and c.contactuid="+c.getUid();
			List<Contact> youContact = contactDAO.findByQuery(hql);//找到我是对方好友的数据
			if(youContact!=null){
				for(Contact contact : youContact){
					contact.setContacttypeid(4);
					contact.setStatus(0);
					contactDAO.attachDirty(contact);//对方把我放到陌生人
				}
			}else{
				hql = "DELETE FROM UserEmailEvent uee WHERE uee.type=3 AND uee.uid="+user.getId()+" AND uee.obj='"+c.getContactemail()+"'";
				contactDAO.deleteByQuery(hql);
			}
			//删除双方群组人员
			String sqlDelContactGroupMapping="delete from ContactGroupMapping map where map.contactuid="+user.getId()+
				" and exists(from ContactGroup group where group.uid="+c.getContactuid()+" and group.id=map.groupid)";
			this.contactGroupMappingDAO.updateByQuery(sqlDelContactGroupMapping);
			sqlDelContactGroupMapping="delete from ContactGroupMapping map where map.contactuid="+c.getContactuid()+
			" and exists(from ContactGroup group where group.uid="+user.getId()+" and group.id=map.groupid)";
			this.contactGroupMappingDAO.updateByQuery(sqlDelContactGroupMapping);
			
			String sqlDelSharemapping="delete from Sharemapping map where map.share2uid="+user.getId()+
				" and exists(from ClipEvent event where event.uid="+c.getContactuid()+" and event.id=map.eventid)";
			this.sharemappingDAO.excuteUpdateQuery(sqlDelSharemapping);
			sqlDelSharemapping="delete from Sharemapping map where map.share2uid="+c.getContactuid()+
			" and exists(from ClipEvent event where event.uid="+user.getId()+" and event.id=map.eventid)";
			this.sharemappingDAO.excuteUpdateQuery(sqlDelSharemapping);
			contactDAO.delete(c);//把对方删除掉
			result="{result:'删除成功',flag:1}";
		}
		return result;
	}
	
	public String delContactByUid(User user, Integer contactuid) {
		String result="{result:'删除失败',flag:0}";
		String hql="FROM Contact c where c.contactuid="+contactuid+" and c.uid="+user.getId();
		List<Contact> myContact = contactDAO.findByQuery(hql);//找到对方是我好友的数据
		if(myContact!=null&&myContact.size()>0){
			hql="FROM Contact c where c.uid="+myContact.get(0).getContactuid()+" and c.contactuid="+myContact.get(0).getUid();
			List<Contact> youContact = contactDAO.findByQuery(hql);//找到我是对方好友的数据
			if(youContact!=null){
				for(Contact contact : youContact){
					contact.setContacttypeid(4);
					contactDAO.attachDirty(contact);//对方把我放到陌生人
				}
				
			}else{
				hql = "DELETE FROM UserEmailEvent uee WHERE uee.type=3 AND uee.uid="+user.getId()+" AND uee.obj='"+myContact.get(0).getContactemail()+"'";
				contactDAO.deleteByQuery(hql);
			}
			//删除双方群组人员
			String sqlDelContactGroupMapping="delete from ContactGroupMapping map where map.contactuid="+user.getId()+
				" and exists(from ContactGroup group where group.uid="+myContact.get(0).getContactuid()+" and group.id=map.groupid)";
			this.contactGroupMappingDAO.updateByQuery(sqlDelContactGroupMapping);
			sqlDelContactGroupMapping="delete from ContactGroupMapping map where map.contactuid="+myContact.get(0).getContactuid()+
			" and exists(from ContactGroup group where group.uid="+user.getId()+" and group.id=map.groupid)";
			this.contactGroupMappingDAO.updateByQuery(sqlDelContactGroupMapping);
			
			String sqlDelSharemapping="delete from Sharemapping map where map.share2uid="+user.getId()+
				" and exists(from ClipEvent event where event.uid="+myContact.get(0).getContactuid()+" and event.id=map.eventid)";
			this.sharemappingDAO.excuteUpdateQuery(sqlDelSharemapping);
			sqlDelSharemapping="delete from Sharemapping map where map.share2uid="+myContact.get(0).getContactuid()+
			" and exists(from ClipEvent event where event.uid="+user.getId()+" and event.id=map.eventid)";
			this.sharemappingDAO.excuteUpdateQuery(sqlDelSharemapping);
			
			contactDAO.delete(myContact.get(0));//把对方删除掉
			result="{result:'删除成功',flag:1}";
		}
		return result;
	}
	/**
	 * 修改联系人
	 */
	public void updateContact(Contact contact){
		contactDAO.attachDirty(contact);
	}
	/**
	 * 对象查找
	 * @param contact
	 * @return
	 */
	public List<Contact> getContactByExample(Contact contact){
		return contactDAO.findByExample(contact);
	}
	/**
	 * 添加联系人
	 * @param contact
	 */
	public void addContact(Contact contact){
		contactDAO.save(contact);
	}
	private void sendEmailInvites(User otherUser,User user,String context){
		String title=otherUser.getName()+"，你有一个来自档期的消息";
		Date date = new Date();
		UserEmailEvent uel = new UserEmailEvent(user.getId(), otherUser.getEmail(), ToolsUtils.htmlEnCode(context), 3, date.getTime());
		userEmailEventDAO.save(uel);
		String href = ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"register_request.html?r="+uel.getCode();
		Map<String, Object> root = new HashMap<String, Object>();
		root.put("name", user.getName());
		root.put("href", href);
		String mailcontent = com.clip.util.FtlUtils.stringRender(root,"inviteFriend.ftl");
		SimpleMailSender.send(mailcontent,title, otherUser.getEmail());
	}
	
	private void sendEmailAddFirend(User otherUser,User user,String context){
		String title=otherUser.getName()+"，你有一个来自档期的消息";
		Date date = new Date();
		UserEmailEvent uel = new UserEmailEvent(user.getId(), otherUser.getEmail(), ""+otherUser.getId(), 3, date.getTime());
		userEmailEventDAO.save(uel);
		String href=ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"user_request.html?r="+uel.getCode();
		Map<String, Object> root = new HashMap<String, Object>();
		root.put("name", otherUser.getName());
		root.put("href", href);
		root.put("fname", user.getName());
		String mailcontent = com.clip.util.FtlUtils.stringRender(root,"addFriend.ftl");
		SimpleMailSender.send(mailcontent,title, otherUser.getEmail());
	}
	public void addEmailContact(User fromuser,int touid,Integer contactType,String content){
		User otherUser = userDAO.findById(touid);
		Contact contact = new Contact();
		contact.setUid(fromuser.getId());
		contact.setName(otherUser.getName());
		contact.setPinyinname(ToolsUtils.chinese2pinyin(otherUser.getName()));
		contact.setContactuid(otherUser.getId());
		contact.setContactemail(otherUser.getEmail());
		contact.setContacttypeid(contactType);
		contact.setStatus(0);
		contactDAO.save(contact);
		sendEmailAddFirend(otherUser,fromuser,content);
	}
	
	/**
	 * 添加Email为联系人(Email存在就可添加)
	 * @param user	登录用户
	 * @param contactName 联系人姓名
	 * @param contactEmail 联系人EMAIL
	 * @param contactType 联系人类型
	 * @param content 联系人发信内容
	 */
	@SuppressWarnings("unchecked")
	public String addEmailContact(User user,String contactName,String contactEmail,Integer contactType,String content){
		String result="";
		String hql="FROM UserEmail ue where ue.email='"+contactEmail+"' and ue.bindable=1";
		List<UserEmail> UEList = contactDAO.findByQuery(hql);
		List<Contact> contactList = null;
		//判断Email是否是网站用户(网站用户包括注册Email和绑定Email)
		if(UEList!=null&&UEList.size()>0){
			if(UEList.get(0).getUid().equals(user.getId())){
				result="{result:'不能添加自己为联系人',flag:0}";
			}else{
				//判断是否已加对方为好友
				User otherUser = userDAO.findById(UEList.get(0).getUid());
				if(judgeRelation(otherUser,user)){
					result="{result:'已是您的联系人',flag:2,uemail:'"+otherUser.getEmail()+"',uname:'"+otherUser.getName()+"',ueemail:'"+contactEmail+"',uename:'"+contactName+"',type:'"+contactTypeDAO.findById(contactType).getTypename()+"'}";
				}else{
					hql="FROM Contact c where c.uid="+user.getId()+" and c.contactuid="+UEList.get(0).getUid();
					contactList = contactDAO.findByQuery(hql);
					if(contactList!=null&&contactList.size()>0){
						List<UserEmailEvent> list=userEmailEventDAO.findUserEmailEventByObj(user, contactEmail, 3);
						if(list==null||list.size()==0){
							sendEmailInvites(otherUser,user,content);
							result="{result:'您的请求已发送请等待对方答复',flag:1}";
						}else{
							UserEmailEvent ue=list.get(0);
							Calendar now=Calendar.getInstance();
							Calendar temp=Calendar.getInstance();
							temp.setTimeInMillis(ue.getActDate());
							temp.add(Calendar.HOUR,12);
							if(temp.getTimeInMillis()<now.getTimeInMillis()){
								this.userEmailEventDAO.delete(ue);
								sendEmailInvites(otherUser,user,content);
								result="{result:'您的请求已发送请等待对方答复',flag:1}";
							}else{
								result="{result:'您的请求已发送请等待对方答复',flag:1}";
							}
						}
					}else{
						//添加对方为好友
						Contact contact = new Contact();
						contact.setUid(user.getId());
						contact.setName(contactName);
						contact.setPinyinname(ToolsUtils.chinese2pinyin(contactName));
						contact.setContactuid(UEList.get(0).getUid());
						contact.setContactemail(contactEmail);
						contact.setContacttypeid(contactType);
						contact.setStatus(0);
						contactDAO.save(contact);
						//发送添加好友邮件
						result="{result:'您的请求已发送请等待对方答复',flag:1}";
					}
					otherUser.setEmail(contactEmail);
					sendEmailAddFirend(otherUser,user,content);
				}
			}
		}else{
			hql="FROM Contact c where c.uid="+user.getId()+" and c.contactemail='"+contactEmail+"'";
			contactList = contactDAO.findByQuery(hql);
			if(contactList!=null&&contactList.size()>0){
				String title="档期邀请好友邮件";
				
				List<UserEmailEvent> list=userEmailEventDAO.findUserEmailEventByObj(user, contactEmail, 3);
				if(list==null||list.size()==0){
					User otherUser = new User(contactEmail,contactName,null,0);
					sendEmailInvites(otherUser,user,content);
				}else{
					UserEmailEvent ue=list.get(0);
					Calendar now=Calendar.getInstance();
					Calendar temp=Calendar.getInstance();
					temp.setTimeInMillis(ue.getActDate());
					temp.add(Calendar.HOUR,12);
					if(temp.getTimeInMillis()<now.getTimeInMillis()){
						this.userEmailEventDAO.delete(ue);
						User otherUser = new User(contactEmail,contactName,null,0);
						sendEmailInvites(otherUser,user,content);
					}
				}
				result="{result:'您的请求已发送请等待对方答复',flag:1}";
			}else{
				Contact contact = new Contact();
				contact.setUid(user.getId());
				contact.setName(contactName);
				contact.setPinyinname(ToolsUtils.chinese2pinyin(contactName));
				contact.setContactuid(0);//等待对方注册或绑定
				contact.setContactemail(contactEmail);
				contact.setContacttypeid(contactType);
				contact.setStatus(0);
				contactDAO.save(contact);
//				//发送邀请邮件
				User otherUser = new User(contactEmail,contactName,null,0);
				sendEmailInvites(otherUser,user,content);
				result="{result:'您的请求已发送请等待对方答复',flag:1}";
			}
		}
		return result;
	}
	
	public String loadRegRequestInfo(String code){
		String result = "<root>";
		User otherUser = null;
		Contact c1 = null;
		UserEmailEvent uel = userEmailEventDAO.checkResetAuthorize(code,3,false);
		if(uel!=null){
			otherUser = userDAO.findById(uel.getUid());
			String hql = "SELECT c FROM Contact c WHERE c.contactemail='"+uel.getObj()+"' AND c.uid="+uel.getUid()+" AND c.contactuid=0";
			List<Contact> list = contactDAO.findByQuery(hql);
			c1 = list!=null&&list.size()>0 ? list.get(0) : null;
			if(c1!=null){
				result+="<selfUser>";
				result+="<name>"+c1.getName()+"</name>";
				result+="<email>"+c1.getContactemail()+"</email>";
				result+="</selfUser>";
				
				result+="<otherUser>";
				result+="<name>"+otherUser.getName()+"</name>";
				result+="<email>"+otherUser.getEmail()+"</email>";
				result+="</otherUser>";
			}
		}
		result += "</root>";
		return result;
	}
	public String loadRquestInfo(String code){
		User selfUser = null;
		User otherUser = null;
		UserEmail userEmail = null;
		UserEmailEvent uel = userEmailEventDAO.checkResetAuthorize(code,3,false);
		String result = "<root>";
		if(uel!=null){
			List<UserEmail> ueList = userEmailDAO.findByEmail(uel.getObj());
			userEmail = ueList!=null&&ueList.size()>0 ? ueList.get(0) : null;
			selfUser = userEmail==null ? null : userDAO.findById(userEmail.getUid());
			otherUser = userDAO.findById(uel.getUid());
			if(selfUser!=null&&otherUser!=null&&userEmail!=null){
				result += "<selfUser>";
				result += "<name>"+selfUser.getName()+"</name>";
				result += "<email>"+userEmail.getEmail()+"</email>";
				result += "</selfUser>";
				result += "<otherUser>";
				result += "<name>"+otherUser.getName()+"</name>";
				result += "<email>"+otherUser.getEmail()+"</email>";
				result += "<buildname>"+userEmail.getEmail()+"</buildname>";
				result += "</otherUser>";
				result += "<message></message>";
			}else{
				result += "<message>获取失败</message>";
			}
			uel.setClick(uel.getClick()+1);
			userEmailEventDAO.update(uel);
		}else{
			result += "<message>该链接无效</message>";
		}
		result += "</root>";
		return result;
	}
	/**
	 * @param otherUser 对方信息
	 * @param selfUser 自己信息
	 * @param userEmail 对方想添加联系人信息(自己Email或绑定Email)
	 * @return
	 */
	public String agree(String code){
		User selfUser = null;
		User otherUser = null;
		UserEmail userEmail = null;
		UserEmailEvent uel = userEmailEventDAO.checkResetAuthorize(code,3,false);
		String result = "<root>";
		if(uel!=null){
			List<UserEmail> ueList = userEmailDAO.findByEmail(uel.getObj());
			userEmail = ueList!=null&&ueList.size()>0 ? ueList.get(0) : null;
			selfUser = userEmail==null ? null : userDAO.findById(userEmail.getUid());
			otherUser = userDAO.findById(uel.getUid());
			if(selfUser!=null&&otherUser!=null&&userEmail!=null){
				contactDAO.addFriend(selfUser, otherUser, userEmail.getEmail());
				result += "<message></message>";
			}else{
				result += "<message>添加失败</message>";
			}
			userEmailEventDAO.delete(uel);
		}else{
			result += "<message>添加失败</message>";
		}
		result += "</root>";
		return result;
	}
	
	/**
	 * 用户不同意添加好友
	 * @param selfUser 对方信息
	 * @param otherUser 自己信息
	 */
	public String refuse(String code){
		User selfUser = null;
		User otherUser = null;
		UserEmail userEmail = null;
		UserEmailEvent uel = userEmailEventDAO.checkResetAuthorize(code,3,false);
		if(uel!=null){
			List<UserEmail> ueList = userEmailDAO.findByEmail(uel.getObj());
			userEmail = ueList!=null&&ueList.size()>0 ? ueList.get(0) : null;
			selfUser = userEmail==null ? null : userDAO.findById(userEmail.getUid());
			otherUser = userDAO.findById(uel.getUid());
			if(selfUser!=null&&otherUser!=null&&userEmail!=null){
				contactDAO.unFriend(selfUser, otherUser, userEmail.getEmail());
			}
			userEmailEventDAO.delete(uel);
		}
		String result = "<root><message></message></root>";
		return result;
	}
	/**
	 * 关系判断
	 * @param otherUser 对方信息
	 * @param selfUser 自己信息
	 * @return
	 */
	public Boolean judgeRelation(User otherUser,User selfUser){
		return judgeRelation(otherUser.getId(),selfUser.getId());
	}
	
	public Boolean judgeRelation(int otheruid,int currentuid){
		boolean b=false;
		String hql = "SELECT c1 FROM Contact c1,Contact c2 WHERE c2.uid="+currentuid+" AND c1.uid="+otheruid+" AND c1.contacttypeid<>4 AND c1.uid=c2.contactuid AND c2.uid=c1.contactuid AND c1.status=c2.status AND c1.status=1 GROUP BY c1.id";
		if(contactDAO.findByQuery(hql).size()>0){
			b=true;
		}
		return b;
	}
	/**
	 * 删除陌生人
	 * @param user
	 * @param id
	 * @return
	 */
	public String delUnknow(User user,Integer id){
		Contact c = null;
		String hql="FROM Contact c where c.id="+id+" and c.uid="+user.getId();
		List<Contact> contactList = contactDAO.findByQuery(hql);
		c = contactList!=null&&contactList.size()>0 ? contactList.get(0) : null;
		if(c!=null){
			hql = "DELETE FROM UserEmailEvent uee WHERE uee.type=3 AND uee.uid="+user.getId()+" AND uee.obj='"+c.getContactemail()+"'";
			contactDAO.deleteByQuery(hql);
			contactDAO.delete(c);
		}
		return "{result:'删除成功',flag:1}";
	}
	/**
	 * 发送邀请
	 * @param user
	 * @param id
	 * @return
	 */
	public String sendInvite(User user,Integer id){
		String result="{result:'邀请发送失败',flag:0}";
		String hql="FROM Contact c where c.id="+id+" and c.uid="+user.getId();
		List<Contact> contactList = contactDAO.findByQuery(hql);
		Contact contact = (contactList!=null&&contactList.size()>0) ? contactList.get(0) : null;
		if(contact!=null){
			this.addEmailContact(user, contact.getName(), contact.getContactemail(), 1, "");
//			User otherUser = new User(contact.getContactemail(),contact.getName(),null,0);
//			String href = ToolsUtils.getWebHeadUrl(null,"01")+"contactAjax!requestInvite.action?content="+ToolsUtils.codingForUT(user.getId()+"-"+contactList.get(0).getContactuid()+"-"+contactList.get(0).getContactemail());
//			sendEmailAddFirend(otherUser,user,href,"");
			result="{result:'邀请已发送,等待对方答复',flag:1}";
		}
		return result;
	}
	public String doInvite(Integer otherId,Integer selfId,String selfEmail){
		String result="添加失败";
		String hql="FROM User u where u.id="+otherId;
		List<User> otherUsers= contactDAO.findByQuery(hql);
		hql="FROM User u where u.id="+selfId;
		List<User> selfUser= contactDAO.findByQuery(hql);
		if(otherUsers.size()>0&&selfUser.size()>0){
			hql = "FROM Contact c WHERE c.uid="+otherId+" AND c.contactuid="+selfId;
			List<Contact> contact1= contactDAO.findByQuery(hql);
			hql="FROM Contact c WHERE c.uid="+selfId+" AND c.contactuid="+otherId;
			List<Contact> contact2= contactDAO.findByQuery(hql);
			if(contact1!=null&&contact1.size()>0){
				if(contact2!=null&&contact2.size()>0){
					contact2.get(0).setContacttypeid(1);
					contact2.get(0).setStatus(1);
					contactDAO.attachDirty(contact2.get(0));
				}else{
					User otherUser=otherUsers.get(0);
					Contact contact = new Contact();
					contact.setUid(selfId);
					String name=otherUser.getName();
					contact.setName(name);
					contact.setPinyinname(ToolsUtils.chinese2pinyin(name));
					contact.setContactuid(otherUser.getId());
					contact.setContactemail(otherUser.getEmail());
					contact.setStatus(1);
					contact.setContacttypeid(1);
					contactDAO.save(contact);
				}
				contact1.get(0).setContacttypeid(1);
				contact1.get(0).setStatus(1);
				contactDAO.attachDirty(contact1.get(0));
				result="添加成功";
			}
		}
		return result;
	}
	public Map organizeMsnContacts(List alreadyfriend, List alreadyregister,
			List none) {
		Map<String, Map> returnMap=new HashMap<String, Map>();
		if(alreadyfriend!=null&&alreadyfriend.size()>0){
			int i=1;
			for (Object object : alreadyfriend) {
				Map<String,Object> temp2=new HashMap<String,Object>();
				MsnContact msnContact=(MsnContact) object;
				temp2.put("displayname","<![CDATA["+msnContact.getDisplayName()+"]]>");
				temp2.put("email", msnContact.getEmail().getEmailAddress());
				returnMap.put("alreadycontact id="+i, temp2);
				i++;
			}
		}
		
		if(alreadyregister!=null&&alreadyregister.size()>0){
			int i=1;
			for (Object object : alreadyregister) {
				Map<String,Object> temp2=new HashMap<String,Object>();
				MsnContact msnContact=(MsnContact) object;
				temp2.put("displayname", "<![CDATA["+msnContact.getDisplayName()+"]]>");
				temp2.put("email", msnContact.getEmail().getEmailAddress());
				returnMap.put("alreadyregister id="+i, temp2);
				i++;
			}
		}
		
		if(none!=null&&none.size()>0){
			int i=1;
			for (Object object : none) {
				Map<String,Object> temp2=new HashMap<String,Object>();
				MsnContact msnContact=(MsnContact) object;
				temp2.put("displayname", "<![CDATA["+msnContact.getDisplayName()+"]]>");
				temp2.put("email", msnContact.getEmail().getEmailAddress());
				returnMap.put("none id="+i, temp2);
				i++;
			}
		}
		return returnMap;
		
	}

	public Map<String, Map> getAllContactsByuid(Integer uid) {
		Map<String, Map> returnMap=new LinkedHashMap<String, Map>();
		String hql="select a FROM Contact a, Contact b where a.uid="+uid+" and a.uid=b.contactuid and a.contactuid=b.uid and a.status=1 and b.status=1";
		List<Contact> newList=this.contactDAO.findByQuery(hql);
		List<User> orderbylist=new ArrayList<User>();
		for(Contact con : newList){
			hql="FROM User u where u.id="+con.getContactuid()+" and u.status=1";
			List<User> userList = userDAO.findByQuery(hql);
			if(userList!=null&&userList.size()>0){
				orderbylist.add(userList.get(0));
			}
		}
		Collections.sort(orderbylist);
		for (User user : orderbylist) {
			Map temp=new HashMap();
			for(Contact con : newList){
				if(con.getContactuid()==user.getId()){
					temp.put("name", con.getName());
					break;
				}
			}
			int userid=user.getId();
			hql="from Usermobileinfo mobile where mobile.uid="+userid+" and status=1";
			List list=this.usermobileinfoDAO.findByQuery(hql);
			if(list!=null&&list.size()>0){
				temp.put("hasmobile",1);
			}else{
				temp.put("hasmobile",0);
			}
			temp.put("email", user.getEmail());
			returnMap.put("user id="+user.getId(),temp);
			
		}
		return returnMap;
	}

	public Map<String, Map> getContactsByName(String nameInput,int uid) {
		Map<String, Map> returnMap=new LinkedHashMap<String, Map>();
		String hql="select a FROM Contact a, Contact b where a.pinyinname like '%"+nameInput+"%' and a.uid="+uid+" and a.uid=b.contactuid and a.contactuid=b.uid and a.status=1 and b.status=1";
		List<Contact> newList=this.contactDAO.findByQuery(hql);
		List<User> orderbylist=new ArrayList<User>();
		for(Contact con : newList){
			hql="FROM User u where u.id="+con.getContactuid()+" and u.status=1";
			List<User> userList = userDAO.findByQuery(hql);
			if(userList!=null&&userList.size()>0){
				orderbylist.add(userList.get(0));
			}
		}
		Collections.sort(orderbylist);
		for (User user : orderbylist) {
			Map temp=new HashMap();
			for(Contact con : newList){
				if(con.getContactuid()==user.getId()){
					temp.put("name", con.getName());
					break;
				}
			}
			int userid=user.getId();
			hql="from Usermobileinfo mobile where mobile.uid="+userid+" and status=1";
			List list=this.usermobileinfoDAO.findByQuery(hql);
			if(list!=null&&list.size()>0){
				temp.put("hasmobile",1);
			}else{
				temp.put("hasmobile",0);
			}
			temp.put("email", user.getEmail());
			returnMap.put("user id="+user.getId(),temp);
			
		}
		// TODO Auto-generated method stub
		return returnMap;
	}

	public List getContactNameAndEmail(User currentUser, int uid) {
		List list=new ArrayList();
		if(currentUser.getId()!=uid){
			List temp=this.contactDAO.findByQuery("from Contact c where c.uid="+currentUser.getId()+" and c.contactuid="+uid);
			if(temp!=null&&temp.size()>0){
				Contact curContact=(Contact) temp.get(0);
				list.add(curContact.getName());
				list.add(curContact.getContactemail());
			}else{
				User user=this.userDAO.findById(uid);
				list.add(user.getName());
				list.add(user.getEmail());
			}
		}else{
			list.add("我");
			list.add("");
		}
		return list;
	}
	
	/**
	 * @param currentuid 
	 * @param otheruid
	 * 		current 与 other的关系
	 * @return 	如果双方是好友，返回备注名
	 * 			如果不是好友，则返回真实名
	 * 			如果是游客，返回真实名
	 */
	public String getUserName(int currentuid,int otheruid){
		if(currentuid==0){
			User user=this.userDAO.findById(otheruid);
			return user.getName();
		}else{
			if(currentuid==otheruid){
				return "我";
			}else{
				List list=this.contactDAO.findByQuery("from Contact c where c.status=1 and c.uid="+currentuid+" and c.contactuid="+otheruid);
				if(list!=null&&list.size()>0){
					Contact contact=(Contact) list.get(0);
					return contact.getName();
				}else{
					User user=this.userDAO.findById(otheruid);
					if(user==null)
						return null;
					else
						return user.getName();
				}
			}
		}
	}

	public List findShareFriendsByEventid(int eventid,User currentUser) {
		String query="select distinct map.uid from ShareAcceptmapping map where map.eventid="+eventid+" and exists (select c.uid from Contact c where c.contactuid="
			+currentUser.getId()+" and c.status=1 and map.uid=c.uid)";
		return this.contactDAO.findByQuery(query);
	}

	public boolean judgeHasInvited(User visitUser, User currentUser) {
		List list=this.contactDAO.findByQuery("from Contact c where c.status=0 and c.uid="+currentUser.getId()+" and c.contactuid="+visitUser.getId());
		if(list!=null&&list.size()>0)
			return true;
		else
			return false;
	}

	public long getUserContactTotalCount(User currentUser, Integer typeid) {
		String query=null;
		if(typeid==4){
			query="select count(*) from Contact c where c.status=0 and c.uid="+currentUser.getId();
		}else{
			query="select count(*) from Contact c where c.status=1 and c.uid="+currentUser.getId();
		}
		List list=this.contactDAO.findByQuery(query);
		if(list!=null&&list.size()>0){
			Long count=(Long ) list.get(0);
			return count.longValue();
		}else
			return 0l;
	}

	public void subscribeCC(int toSubscribeuid, User currentUser) {
		List list=this.contactDAO.findByQuery("from Contact c where c.status=1 and c.contacttypeid=2 and c.uid="+toSubscribeuid+" and c.contactuid="+currentUser.getId());
		if(list!=null&&list.size()>0){
			return;
		}else{
			Contact contact=new Contact();
			contact.setUid(toSubscribeuid);
			contact.setName(currentUser.getName());
			contact.setPinyinname(ToolsUtils.chinese2pinyin(currentUser.getName()));
			contact.setContacttypeid(2);
			contact.setContactemail(currentUser.getEmail());
			contact.setStatus(1);
			contact.setCreatetime(Calendar.getInstance().getTimeInMillis());
			contact.setContactuid(currentUser.getId());
			this.contactDAO.save(contact);
		}
	}

	public void unsubscribeCC(int toUnsubscribeuid, User currentUser) {
		List list=this.contactDAO.findByQuery("from Contact c where c.status=1 and c.contacttypeid=2 and c.uid="+toUnsubscribeuid+" and c.contactuid="+currentUser.getId());
		if(list!=null&&list.size()>0){
			this.contactDAO.deleteByQuery("delete from Contact c where c.status=1 and c.contacttypeid=2 and c.uid="+toUnsubscribeuid+" and c.contactuid="+currentUser.getId());
		}else{
			return;
		}
	}

	public List getAllSubscribedUsers(int uid,int currentpage, int pagesize) {
		List list=this.contactDAO.pagingByQuery("from Contact c where c.status=1 and c.contacttypeid=2 and c.uid="+uid+" order by c.createtime desc",currentpage,pagesize);
		return list;
	}

	public Long countAllSubscribedUsers(int uid) {
		return this.contactDAO.countByQuery("select count(*) from Contact c where c.status=1 and c.contacttypeid=2 and c.uid="+uid);
	}

	public List getContactByUid(int uid, String groupids, int needpagenum) {
		String query=null;
		if(groupids!=null&&groupids.length()>0){
			query="from Contact c where c.status=1 and c.contacttypeid=1 and c.uid="+uid+" and exists(select map.id from ContactGroupMapping map where map.groupid in ("+groupids+") and map.contactuid=c.contactuid) order by c.pinyinname";
		}else{
			query="from Contact c where c.status=1 and c.contacttypeid=1 and c.uid="+uid+" order by c.pinyinname";
		}
		if(needpagenum==-1||needpagenum==0){
			return this.contactDAO.findByQuery(query);
		}else if(needpagenum>0){
			return this.contactDAO.pagingByQuery(query,needpagenum-1,ContactService.APPCONTACTLENGTH);
		}else{
			return null;
		}
	}

	public void addUserContacts(User currentUser, String uids) {
		List<Integer> array=new ArrayList<Integer>();
		if(uids.indexOf(",")>0){
			String[]ids=uids.split(",");
			for (String string : ids) {
				array.add(Integer.parseInt(string));
			}
		}else{
			array.add(Integer.parseInt(uids));
		}
		Calendar now=Calendar.getInstance();
		for (Integer uid : array) {
			User user=this.userDAO.findById(uid);
			String query1="from Contact c where c.uid=? and c.contactuid=?";
			List list1=this.contactDAO.findByQuery(query1,new Object[]{currentUser.getId(),user.getId()});
			//判断是不是已经是好友
			boolean isfriend=false;
			if(list1!=null&&list1.size()>0){
				Contact temp=(Contact) list1.get(0);
				if(temp.getStatus()==1){
					isfriend=true;
				}else if(temp.getStatus()==0){
					//说明对方已经有意向添加您为好友
					temp.setStatus(1);
					temp.setCreatetime(now.getTimeInMillis());
					this.contactDAO.attachDirty(temp);
					List list3=this.contactDAO.findByQuery(query1, new Object[]{user.getId(),currentUser.getId()});
					if(list3!=null&&list3.size()>0){
						Contact temp2=(Contact) list3.get(0);
						if(temp2.getStatus()==0){
							temp2.setStatus(1);
							temp2.setCreatetime(now.getTimeInMillis());
							this.contactDAO.attachDirty(temp2);
						}
					}else{
						Contact newobj=new Contact();
						newobj.setUid(user.getId());
						newobj.setContactuid(currentUser.getId());
						newobj.setName(currentUser.getName());
						newobj.setPinyinname(ToolsUtils.chinese2pinyin(currentUser.getName()));
						newobj.setContacttypeid(1);
						newobj.setContactemail(currentUser.getEmail());
						newobj.setStatus(1);
						newobj.setCreatetime(now.getTimeInMillis());
						this.contactDAO.save(newobj);
					}
					isfriend=true;
					String query2="delete from UserEmailEvent event where event.uid="+user.getId()+" and event.obj="+currentUser.getEmail()+" and event.type=3";
					this.userEmailEventDAO.executeQuery(query2);
					query2="delete from UserEmailEvent event where event.uid="+currentUser.getId()+" and event.obj="+user.getEmail()+" and event.type=3";
					this.userEmailEventDAO.executeQuery(query2);
				}
			}
			if(isfriend){
				continue;
			}else{
				
					//判断是否已经发送过好友请求给对方
				String query4="from UserEmailEvent event where event.uid=? and event.obj=? and event.type=3";
				List list4=this.userEmailEventDAO.findByQuery(query4,currentUser.getId(),user.getEmail());
				if(list4==null||list4.size()==0){
					Contact contact = new Contact();
					contact.setUid(currentUser.getId());
					contact.setName(user.getName());
					contact.setPinyinname(ToolsUtils.chinese2pinyin(user.getName()));
					contact.setContactuid(user.getId());
					contact.setContactemail(user.getEmail());
					contact.setContacttypeid(1);
					contact.setStatus(0);
					contactDAO.save(contact);
//					private void sendEmailAddFirend(User otherUser,User user,String context){
					String title=user.getName()+"，你有一个来自档期的消息";
					UserEmailEvent uel = new UserEmailEvent(currentUser.getId(), user.getEmail(), ""+user.getId(), 3, now.getTimeInMillis());
					userEmailEventDAO.save(uel);
					String href=ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"user_request.html?r="+uel.getCode();
					Map<String, Object> root = new HashMap<String, Object>();
					root.put("name", user.getName());
					root.put("href", href);
					root.put("fname", currentUser.getName());
					String mailcontent = com.clip.util.FtlUtils.stringRender(root,"addFriend.ftl");
					List emails=getUserNoticedEmail(user.getId());
					for (int i = 0; i < emails.size(); i++) {
						String tempemail=(String) emails.get(i);
						SimpleMailSender.send(mailcontent,title,tempemail );
					}
				}
			}
		}
	}

	public void addContacts(User currentUser, String requestuids, int responsestatus) {
		List<Integer> array=new ArrayList<Integer>();
		if(requestuids.indexOf(",")>0){
			String[]ids=requestuids.split(",");
			for (String string : ids) {
				array.add(Integer.parseInt(string));
			}
		}else{
			array.add(Integer.parseInt(requestuids));
		}
		for (Integer requestuid : array) {
			addContact(currentUser,requestuid,responsestatus);
		}
	}
	
	public String addContact(User currentUser,int requestuid,int responsestatus){
		User requestUser=this.userDAO.findById(requestuid);
		String query1="from Contact c where c.uid=? and c.contactuid=?";
		if(responsestatus==1){//接受
			List list1=this.contactDAO.findByQuery(query1, new Object[]{requestuid,currentUser.getId()});
			if(list1!=null&&list1.size()>0){
				Contact temp2=(Contact) list1.get(0);
				if(temp2.getStatus()==0){
					temp2.setStatus(1);
					this.contactDAO.attachDirty(temp2);
				}
			}else{
				return "不允许添加该好友";
			}
			List list2=this.contactDAO.findByQuery(query1, new Object[]{currentUser.getId(),requestuid});
			if(list2!=null&&list2.size()>0){
				Contact temp2=(Contact) list2.get(0);
				if(temp2.getStatus()!=1){
					temp2.setStatus(1);
					this.contactDAO.attachDirty(temp2);
				}
			}else{
				
				Contact newobj=new Contact();
				newobj.setUid(currentUser.getId());
				newobj.setContactuid(requestUser.getId());
				newobj.setName(requestUser.getName());
				newobj.setPinyinname(ToolsUtils.chinese2pinyin(requestUser.getName()));
				newobj.setContacttypeid(1);
				newobj.setContactemail(requestUser.getEmail());
				newobj.setStatus(1);
				newobj.setCreatetime(Calendar.getInstance().getTimeInMillis());
				this.contactDAO.save(newobj);
			}
			//移除双方的好友请求
			String query2="delete from UserEmailEvent event where event.uid="+requestUser.getId()+" and event.obj='"+currentUser.getEmail()+"' and event.type=3";
			this.userEmailEventDAO.executeQuery(query2);
			query2="delete from UserEmailEvent event where event.uid="+currentUser.getId()+" and event.obj='"+requestUser.getEmail()+"' and event.type=3";
			this.userEmailEventDAO.executeQuery(query2);
			return null;
		}else{//拒绝
			String query2="from UserEmailEvent event where event.uid=? and event.obj=? and event.type=3";
			List list2=this.userEmailEventDAO.findByQuery(query2, new Object[]{requestuid,currentUser.getEmail()});
			if(list2!=null&&list2.size()>0){
				UserEmailEvent emailEvent=(UserEmailEvent) list2.get(0);
				this.userEmailEventDAO.delete(emailEvent);
			}
			
			List list3=this.contactDAO.findByQuery(query1,new Object[]{requestuid,currentUser.getId()});
			if(list3!=null&&list3.size()>0){
				Contact contact=(Contact) list3.get(0);
				if(contact.getStatus()==1){
					List list4=this.contactDAO.findByQuery(query1,new Object[]{currentUser.getId(),requestuid});
					if(list4!=null&&list3.size()>0){
						return null;
					}
				}else
					this.contactDAO.delete(contact);
			}else{
				return null;
			}
			Map<String, Object> root = new HashMap<String, Object>();
			root.put("name", requestUser.getName());
			root.put("fname", currentUser.getName());
			String mailcontent = com.clip.util.FtlUtils.stringRender(root,"refuseAddFriend.ftl");
			List list=getUserNoticedEmail(requestuid);
			for (Object object : list) {
				String email=(String) object;
				SimpleMailSender.send(mailcontent,requestUser.getName()+"，你有一个来自档期的消息", email);
			}
			return null;
		}
	}

	private List getUserNoticedEmail(int uid){
		String query="from UserEmail email where email.uid=? and email.bindable=1 and email.status=1";
		List emaillist=this.userEmailDAO.findByQuery(query,new Object[]{uid});
		List reList=new ArrayList();
		for (int i = 0; i < emaillist.size(); i++) {
			UserEmail userEmail=(UserEmail) emaillist.get(0);
			String email=userEmail.getEmail();
			reList.add(email);
		}
		return reList;
	}
	//[{"key":String,"name":String,"mobiles":[{"mobile":String}],"emails":[{"email":String}]}]
	public List<AppContact> analyzeContactsJSONArray(int currentuid,JSONArray array) {
		List<AppContact> list=new ArrayList<AppContact>();
		for (int i = 0; i < array.size(); i++) {
			AppContact appContact=new AppContact();
			JSONObject jsonObject=(JSONObject) array.get(i);
			if(jsonObject.get("key")!=null)
				appContact.setKey((String)jsonObject.get("key"));
			appContact.setName((String)jsonObject.get("name"));
			Object mobj=jsonObject.get("mobiles");
			if(mobj!=null){
				JSONArray marr=(JSONArray) mobj;
				for (int j = 0; j < marr.size(); j++) {
					JSONObject phoneobj=(JSONObject) marr.get(j);
					AppPhone appPhone=new AppPhone();
					appPhone.setPhonenum((String)phoneobj.get("mobile"));
					int existuid=checkMobilePhoneOwner(appPhone.getPhonenum());
					appPhone.setUid(existuid);
					if(existuid>0){
						boolean isfriend=this.judgeRelation(existuid, currentuid);
						appPhone.setIsfriend(isfriend);
					}
					appContact.getPhones().add(appPhone);
				}
			}
			Object eobj=jsonObject.get("emails");
			if(eobj!=null){
				JSONArray earr=(JSONArray) eobj;
				for (int j = 0; j < earr.size(); j++) {
					JSONObject emailobj=(JSONObject) earr.get(j);
					AppEmail appEmail=new AppEmail();
					appEmail.setEmail((String)emailobj.get("email"));
					int existuid=checkEmailOwner(appEmail.getEmail());
					appEmail.setUid(existuid);
					if(existuid>0){
						boolean isfriend=this.judgeRelation(existuid, currentuid);
						appEmail.setIsfriend(isfriend);
					}
					appContact.getEmails().add(appEmail);
				}
			}
			Object sobj=jsonObject.get("sinas");
			if(eobj!=null){
				JSONArray sarr=(JSONArray) sobj;
				for (int j = 0; j < sarr.size(); j++) {
					JSONObject sinaobj=(JSONObject) sarr.get(j);
					AppWeibo appWeibo=new AppWeibo();
					appWeibo.setSinauid((String)sinaobj.get("sinauid"));
					int existuid=checkSinauidOwner(appWeibo.getSinauid());
					appWeibo.setUid(existuid);
					if(existuid>0){
						boolean isfriend=this.judgeRelation(existuid, currentuid);
						appWeibo.setIsfriend(isfriend);
					}
					appContact.getWeibos().add(appWeibo);
				}
			}
		}
		return list;
	}
	
	private int checkSinauidOwner(String sinauid) {
		String query="from Userassina e where e.sinauid='"+sinauid+"'";
		List list=this.userEmailDAO.findByQuery(query);
		if(list!=null&&list.size()>0){
			Userassina userassina=(Userassina) list.get(0);
			return userassina.getUid();
		}else{
			return 0;
		}
	}

	public int checkEmailOwner(String email) {
		String query="from UserEmail e where e.status=1 and e.email='"+email+"'";
		List list=this.userEmailDAO.findByQuery(query);
		if(list!=null&&list.size()>0){
			UserEmail useremail=(UserEmail) list.get(0);
			return useremail.getUid();
		}else{
			return 0;
		}
	}

	public int checkMobilePhoneOwner(String phonenum){
		String query="from Usermobileinfo m where m.status=1 and m.mobilenum='"+phonenum+"'";
		List list=this.usermobileinfoDAO.findByQuery(query);
		if(list!=null&&list.size()>0){
			Usermobileinfo usermobileinfo=(Usermobileinfo) list.get(0);
			return usermobileinfo.getUid();
		}else{
			return 0;
		}
	}

	
	public List getCurrentUserContacts(int uid,List circlememberlist){
		String hql = "SELECT c1 FROM Contact c1,Contact c2 WHERE c1.uid="+uid+" AND c1.uid=c2.contactuid AND c2.uid=c1.contactuid AND c1.status=1 AND c2.status=1 order by c1.pinyinname";
		List<Contact> newList=contactDAO.findByQuery(hql);
		List<Contact> returnList=new ArrayList<Contact>();
		for(Contact con : newList){
			if(circlememberlist.size()>0&&circlememberlist.contains(con.getContactuid())){
				continue;
			}else
				returnList.add(con);
		}
		return returnList;
	}
}